package com.zj.joke.adapter;

import java.util.ArrayList;
import java.util.List;

import com.zj.joke.R;
import com.zj.joke.db.DBItem;

import android.R.integer;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class DBItemAdapter extends BaseAdapter {
	private List<DBItem> mItems = new ArrayList<DBItem>();
	private Context mContext;
	private int[] mRes = { R.drawable.ic_item_1, R.drawable.ic_item_2,
			R.drawable.ic_item_3, R.drawable.ic_item_4, R.drawable.ic_item_5 };

	public DBItemAdapter(Context context) {
		this.mContext = context;
	}

	public void setDBItems(List<DBItem> objects) {
		mItems.clear();
		if (objects != null) {
			for (DBItem object : objects) {
				mItems.add(object);
			}
		}
		notifyDataSetChanged();
	}

	public void addDBItems(List<DBItem> objects) {
		if (objects != null) {
			for (DBItem object : objects) {
				mItems.add(object);
			}
		}
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return mItems.size();
	}

	@Override
	public Object getItem(int position) {
		return mItems.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder vh = null;
		if (convertView == null) {
			vh = new ViewHolder();
			convertView = LayoutInflater.from(mContext).inflate(
					R.layout.item_show, null);
			vh.titleTv = (TextView) convertView.findViewById(R.id.title);
			vh.contentTv = (TextView) convertView.findViewById(R.id.content);
			convertView.setTag(vh);
		} else {
			vh = (ViewHolder) convertView.getTag();
		}
		convertView.setBackgroundResource(mRes[position % mRes.length]);
		vh.titleTv.setText(mItems.get(position).title);
		vh.contentTv.setText(mItems.get(position).text);
		return convertView;
	}

	class ViewHolder {
		TextView titleTv;
		TextView contentTv;
	}
}
